<template>
    <div class="min-h-screen bg-white flex flex-col md:flex-row">
        <!-- 移除了移动端顶部背景 -->

        <!-- 登录表单区域 - 调整为在移动端上下居中 -->
        <div class="p-4 md:p-8 flex flex-col w-full md:w-[75%] bg-white md:bg-[url('@/assets/images/login/logo-bg2.png')] md:bg-cover md:bg-center md:bg-no-repeat min-h-screen flex items-center justify-center">
            <div class="w-full max-w-[360px] bg-white p-6 md:p-8 rounded-lg md:shadow-xl md:border relative">
                <!-- 登录方式切换 -->
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-xl font-bold text-slate-950">
                        {{ loginType === 'phone' ? '手机号登录' : '账号密码登录' }}
                    </h2>
                    <button @click="loginType = loginType === 'phone' ? 'password' : 'phone'"
                        class="text-sm text-[#2970FF] hover:text-[#2970FF]/80">
                        {{ loginType === 'phone' ? '账号密码登录' : '手机号登录' }}
                    </button>
                </div>

                <!-- 手机号登录表单 -->
                <div v-if="loginType === 'phone'" class="space-y-4">
                    <div>
                        <input v-model="phone" type="tel" placeholder="请输入手机号"
                            class="w-full h-12 px-4 border border-gray-200 rounded-md focus:outline-none focus:border-[#2970FF]">
                    </div>
                    <div class="relative">
                        <input v-model="verifyCode" type="text" placeholder="请输入验证码"
                            class="w-full h-12 px-4 border border-gray-200 rounded-md focus:outline-none focus:border-[#2970FF]">
                        <button @click="sendVerifyCode" :disabled="cooldown > 0"
                            class="absolute right-4 top-1/2 -translate-y-1/2 text-[#2970FF] text-sm disabled:text-gray-400">
                            {{ cooldown > 0 ? `${cooldown}s` : '获取验证码' }}
                        </button>
                    </div>
                    <button @click="handlePhoneLogin"
                        class="w-full h-12 bg-[#2970FF] text-white text-sm rounded-md hover:bg-[#2970FF]/90">
                        登录/注册
                    </button>
                </div>

                <!-- 账号密码登录表单 -->
                <div v-else class="space-y-4">
                    <div>
                        <input v-model="username" type="text" placeholder="请输入账号"
                            class="w-full h-12 px-4 border border-gray-200 rounded-md focus:outline-none focus:border-[#2970FF]">
                    </div>
                    <div>
                        <input v-model="password" type="password" placeholder="请输入密码"
                            class="w-full h-12 px-4 border border-gray-200 rounded-md focus:outline-none focus:border-[#2970FF]">
                    </div>
                    <button @click="handlePasswordLogin"
                        class="w-full h-12 bg-[#2970FF] text-white text-sm rounded-md hover:bg-[#2970FF]/90">
                        登录
                    </button>
                </div>

                <!-- 用户协议 -->
                <div class="mt-6 text-center text-xs text-gray-400">
                    登录即表示同意
                    <a href="#" class="text-[#2970FF]">《用户协议》</a>
                    和
                    <a href="#" class="text-[#2970FF]">《隐私政策》</a>
                </div>
            </div>
        </div>

        <!-- 桌面端右侧背景图 -->
        <div class="hidden md:block flex-1 relative w-[25%]">
            <div
                class="absolute inset-0 bg-[#F7F8FA] bg-[url('@/assets/images/login/logo-bg.png')] bg-cover bg-center bg-no-repeat">
                <div
                    class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[80%] h-[80%] bg-[url('@/assets/images/login/back.png')] bg-contain bg-center bg-no-repeat z-10">
                    <div class="relative h-full flex items-center justify-center z-20">
                        <div class="text-center">
                            <h3 class="text-3xl font-bold mb-2 text-slate-950">出题、练题、考试</h3>
                            <p class="text-3xl font-bold text-slate-950 mb-1">快人一步</p>
                            <p class="text-base font-normal pt-8">各种学习题目，百万文字，不限限制，快速生成题目</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { setUserInfo } from '@/utils/auth'
import { userApi } from '@/api'  // 添加这行导入

const router = useRouter()
const route = useRoute()
const loginType = ref('phone')
const phone = ref('')
const username = ref('')
const password = ref('')
const verifyCode = ref('')
const cooldown = ref(0)
const qrCode = ref('') // 这里需要替换为实际的二维码图片路径

// 验证手机号
const validatePhone = () => {
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phone.value) {
        ElMessage.error('请输入手机号')
        return false
    }
    if (!phoneRegex.test(phone.value)) {
        ElMessage.error('请输入正确的手机号')
        return false
    }
    return true
}

// 发送验证码
const sendVerifyCode = async () => {
    if (cooldown.value > 0) return
    if (!validatePhone()) return

    try {
        await userApi.loginSms(phone.value)
        ElMessage.success('验证码发送成功')
        cooldown.value = 60
        const timer = setInterval(() => {
            cooldown.value--
            if (cooldown.value <= 0) {
                clearInterval(timer)
            }
        }, 1000)
    } catch (error) {
        ElMessage.error('验证码发送失败')
    }
}

// 处理登录成功后的操作
const handleLoginSuccess = (userInfo) => {
    ElMessage.success('登录成功')
    
    // 直接跳转到目标路径
    setTimeout(() => {
        if (!userInfo.children || userInfo.children.length === 0) {
            router.push('/student/first')
        } else {
            router.push('/homeFilled')
        }
    }, 300)
}

// 手机号短信登录
const handlePhoneLogin = async () => {
    if (!validatePhone()) return
    if (!verifyCode.value) {
        ElMessage.error('请输入验证码')
        return
    }

    // 新增验证码格式验证
    const codeRegex = /^\d{6}$/
    if (!codeRegex.test(verifyCode.value)) {
        ElMessage.error('验证码必须是6位纯数字')
        return
    }

    try {
        const response = await userApi.smsLogin({
            mobile: phone.value,
            code: verifyCode.value
        })

        // 存储Authorization到localStorage
        localStorage.setItem('Authorization', response)

        const userInfo = await userApi.getUserInfo()
        // 保存接口返回的用户信息
        setUserInfo(userInfo)
        
        handleLoginSuccess(userInfo)
    } catch (error) {
        console.error(error)
        ElMessage.error('登录失败，请重试')
    }
}

// 手机号密码登录
const handlePasswordLogin = async () => {
    if (!username.value) {
        ElMessage.error('请输入账号')
        return
    }
    if (!password.value) {
        ElMessage.error('请输入密码')
        return
    }

    try {
        const response = await userApi.mobileLogin({
            mobile: username.value,
            pwd: password.value
        })
        
        // 存储Authorization到localStorage
        localStorage.setItem('Authorization', response)

        const userInfo = await userApi.getUserInfo()
        // 保存接口返回的用户信息
        setUserInfo(userInfo)
        
        handleLoginSuccess(userInfo)
    } catch (error) {
        ElMessage.error('登录失败，请重试')
    }
}
</script>

<style scoped></style>